// 引入gulp及相关模块
var gulp = require("gulp");
var { src, dest, series, parallel, watch} = gulp;
var cleanCss = require("gulp-clean-css");
var autoPreFix = require("gulp-autoprefixer");
var sass = require("gulp-sass");
var uglify = require("gulp-uglify");
var babel = require("gulp-babel");
var htmlmin = require("gulp-htmlmin");
var clean = require("gulp-clean");
var server = require("gulp-webserver");

// 定义任务
// 处理css
function doCss() {
    return src("./src/scss/**/*.scss")
        .pipe(sass())
        .pipe(autoPreFix())
        .pipe(cleanCss())
        .pipe(dest("./dist/css/"))
}
// 处理html
function doHTML() {
    return src("./src/**/*.html")
        .pipe(htmlmin({
            // 是否压缩空白
            "collapseWhitespace": true,
            // 是否压缩style标签及其中的css代码
            "minifyCSS": true,
            // 是否压缩script标签及其中的js代码
            "minifyJS": true,
            // 是否移除没有属性值的HTML标准属性
            "removeEmptyAttributes": true,
            "ignoreCustomComment": true,
            "removeComments": true
        }))
        .pipe(dest("./dist/"))
}
function doJS() {
    return src("./src/js/**/*.js")
        // .pipe(uglify())
        .pipe(babel({
            presets: ["es2015"]
            // 如果下载的模块是 babel-preset-es2015 数组里就得是"es2015" 
            // 如果下载的模块是 babel-preset-env 数组里就得是 "env"
        }))
        .pipe(dest("./dist/js/"))
}

function move() {
    return src("./src/libs/**/*.*")
        .pipe(dest("./dist/libs/"))
}
function move2() {
    return src("./src/data/*.*")
        .pipe(dest("./dist/data/"))
}
function move3() {
    return src("./src/images/*.*")
        .pipe(dest("./dist/images/"))
}

function cleanFiles() {
    return src("./dist/")
        .pipe(clean())
}

function startServer() {
    return src("./dist")
        .pipe(server({
            // 主机名
            // host: "10.30.153.93",
            // 端口号
            port: 3000,
            // 热更新 
            livereload: true,
            // 打开的主页
            open: "./index.html",
            // 当请求失败时的替代响应
            fallback: "./index.html",
            // 配置代理
            // proxy
            proxies: [
                {
                    source:"/php/",
                    target: "http://localhost:80/php/",
                }
            ]
        }))
}

module.exports.doCss = doCss;
module.exports.doHTML = doHTML;
module.exports.doJS = doJS;
module.exports.move = move;
module.exports.cleanFiles = cleanFiles;
module.exports.all = series(cleanFiles, parallel(doCss, doJS, doHTML, move,move2,move3))
module.exports.watch= function () {
    return watch("./src/", series(cleanFiles, parallel(doCss, doJS, doHTML, move,move2,move3)))
}
module.exports.startServer = startServer;